package com.xuecheng.orders.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.xuecheng.orders.exception.OrdersAlipayClientCreateFailedException;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 勾新杰
 * @version 1.0
 * @description 支付宝配置参数
 * @date 2022/10/20 22:45
 */
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(AliPayProperties.class)
public class AliPayConfig {

    /**
     * 支付宝配置参数
     */
    private final AliPayProperties aliPayProperties;

    /**
     * 支付宝客户端
     *
     * @return AlipayClient
     */
    @Bean
    public AlipayClient alipayClient() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(aliPayProperties.getUrl());
        alipayConfig.setAppId(aliPayProperties.getAppid());
        alipayConfig.setPrivateKey(aliPayProperties.getPrivateKey());
        alipayConfig.setFormat(aliPayProperties.getFormat());
        alipayConfig.setCharset(aliPayProperties.getCharset());
        alipayConfig.setSignType(aliPayProperties.getSignType());
        alipayConfig.setAlipayPublicKey(aliPayProperties.getAlipayPublicKey());
        try {
            return new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            throw new OrdersAlipayClientCreateFailedException();
        }
    }
}
